/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： InitService.java
 * Date：18-11-5 上午10:54
 * Author: guomw
 */

package com.guomw.report.service.service;

import com.guomw.report.common.utils.PropertyUtil;
import com.guomw.report.service.entity.SystemManager;
import com.guomw.report.service.entity.SystemMenu;
import com.guomw.report.service.entity.SystemRole;
import com.guomw.report.service.enums.RoleType;
import com.guomw.report.service.repository.system.SystemManagerRepository;
import com.guomw.report.service.repository.system.SystemMenuRepository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目初始化
 *
 * @author guomw
 * @date 2018/9/17
 */
@Service
public class InitService {
    private static final Log log = LogFactory.getLog(InitService.class);

    @Autowired
    private SystemService systemService;
    @Autowired
    private SystemManagerRepository systemManagerRepository;

    @Autowired
    private SystemMenuRepository systemMenuRepository;

    private SystemManager manager;

    @PostConstruct
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public void init() {
        initSystemManager();
        initSystemMenu();
    }

    /**
     * 初始化系统管理员
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void initSystemManager() {
        if (systemManagerRepository.count() == 0) {
            LocalDateTime dateTime = LocalDateTime.now();
            SystemRole role = new SystemRole();
            role.setEnable(true);
            role.setRoleName("超级管理员");
            role.setRoleType(RoleType.Default.getCode());
            role.setCreateTime(dateTime);
            role.setAuthority("");
            role.setUserId(-1);
            role = systemService.saveRole(role);
            manager = new SystemManager();
            manager.setRole(role);
            manager.setCreateTime(dateTime);
            manager.setLoginName(PropertyUtil.getProperty("user"));
            manager.setEnable(true);
            manager.setParentUserId(0);
            try {
                manager.setLoginPwd(DigestUtils.md5DigestAsHex(PropertyUtil.getProperty("password").getBytes("UTF-8")).toLowerCase());
            } catch (UnsupportedEncodingException e) {
                log.info(e);
            }
            manager.setLastLoginTime(dateTime);
            systemService.saveManager(manager);
        }
    }

    /**
     * 初始化系统菜单
     */
    public void initSystemMenu() {
        List<SystemMenu> menuList = systemMenuRepository.findAll();
        if (menuList == null || menuList.size() == 0) {
            boolean isFunction = false;
            SystemMenu menu = saveMenu(0, "系统配置", 50, "none", "cogs", isFunction, null);
            Integer pid = menu.getItemCode();
            //功能权限
            Map<String, String> functionMap = new HashMap<>();
            functionMap.put("/sys/ajax/save", "添加和编辑");
            functionMap.put("/sys/ajax/list", "列表");
            functionMap.put("/sys/ajax/details", "详情");
            functionMap.put("/sys/ajax/activate", "设置状态");
            functionMap.put("/sys/ajax/delete", "删除");
            saveMenu(pid, "菜单管理", 1, "/sys/menus", "bars", isFunction, functionMap);

            functionMap.clear();
            functionMap.put("/sys/ajax/rolelist", "列表");
            functionMap.put("/sys/ajax/editrole", "添加和编辑");
            functionMap.put("/sys/ajax/deleterole", "删除");
            functionMap.put("/sys/ajax/setpower", "设置权限");
            functionMap.put("/sys/ajax/setenable", "设置状态");
            functionMap.put("/sys/ajax/list", "权限列表");
            saveMenu(pid, "角色管理", 2, "/sys/roles", "user", isFunction, functionMap);

            functionMap.clear();
            functionMap.put("/sys/ajax/editmanager", "添加和编辑");
            functionMap.put("/sys/ajax/managerlist", "列表");
            functionMap.put("/sys/ajax/setuserenable", "设置状态");
            saveMenu(pid, "账户管理", 3, "/sys/manager", "users", isFunction, functionMap);


            //用户管理
            menu=saveMenu(0, "用户管理", 1, "none", "file-text-o", isFunction, null);
            pid = menu.getItemCode();
            functionMap.clear();
            functionMap.put("/user/ajax/genetesting", "列表");
            saveMenu(pid, "基因检测用户", 1, "/user/list", "list", isFunction, functionMap);
            //桌面
            saveMenu(0, "桌面", 0, "/desktop", "desktop", isFunction, null);
        }
    }

    /**
     * 保存功能菜单
     *
     * @param pid
     * @param title
     * @param url
     */
    private void saveFunctionMenu(Integer pid, String title, String url) {
        saveMenu(pid, title, 1, url, "", true, null);
    }

    /**
     * 保存菜单
     *
     * @param pid
     * @param title
     * @param sort
     * @param url
     * @param iconCls
     * @return
     */
    private SystemMenu saveMenu(Integer pid, String title, int sort, String url, String iconCls, boolean isFunction, Map<String, String> functionMap) {
        return saveMenu(pid, title, sort, url, iconCls, true, isFunction, functionMap);
    }

    private SystemMenu saveMenu(Integer pid, String title, int sort, String url, String iconCls, boolean isEnable, boolean isFunction, Map<String, String> functionMap) {
        SystemMenu menu = new SystemMenu();
        menu.setCreateTime(LocalDateTime.now());
        menu.setItemParentCode(pid);
        menu.setItemEnable(isEnable);
        menu.setItemName(title);
        menu.setItemSort(sort);
        menu.setItemPath(url);
        menu.setItemIconCls(iconCls);
        menu.setItemFunction(isFunction);
        menu.setItemChildCount(Long.valueOf(0));
        systemService.save(menu);
        Integer itemCode = menu.getItemCode();
        if (functionMap != null) {
            functionMap.forEach((key, value) -> saveFunctionMenu(itemCode, value, key));
        }
        return menu;
    }
}

